package com.tarena.lbs.basic.web.filters;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.thread.AuthenticationUtil;
import com.tarena.lbs.basic.web.thread.CustomThreadLocal;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
@Slf4j
public class AuthenticationFilter implements Filter {
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    @Autowired
    private CustomThreadLocal<UserPrinciple> customThreadLocal;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始执行 认证解析jwt的过程");
        Thread thread = Thread.currentThread();
        log.info("过滤器开始执行,当前线程:{}",thread);
        //1.判断请求是否是http请求
        if (servletRequest instanceof HttpServletRequest) {
            //是http请求
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            //2.获取请求头
            String jwt = req.getHeader("Authorization");
            //3.判断是否是空 不空
            if (jwt != null && jwt.length()>0) {
                try {
                    UserPrinciple userPrinciple =
                            jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
//                    customThreadLocal.save(userPrinciple);
                    AuthenticationUtil.save(userPrinciple);
                    log.info("解析jwt成功,拿到用户认证对象:{}",userPrinciple);
                } catch (BusinessException e) {
                    log.error("解析jwt失败",e);
                }
            }
        }
        //thread = Thread.currentThread();
        //log.info("过滤器执行完成,当前线程:{}",thread);
        //调用过滤链对象，将请求和相应向后调用
        filterChain.doFilter(servletRequest, servletResponse);
        //在请求 响应即将返回的时候,将当前请求线程数据清空
        AuthenticationUtil.clear();

    }
}
